<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>兑换礼品</title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" href="../css/1px.css" />
	</head>
	<style>
		html {
			font-family: Roboto, Arial, "Noto Sans CJK SC", "Noto Sans CJK TC", "Pingfang SC", "Microsoft Yahei", "WenQuanYi Micro Hei", sans-serif;
		}
		
		body {
			overflow-x: hidden;
			background-color: #fff !important;
		}
		
		.mui-content {
			background-color: #fff;
		}
		/*头像*/
		
		.flex {
			display: flex;
		}
		
		.user-info {
			padding: 3px 0;
		}
		
		.header {
			flex: 3;
			text-align: center;
		}
		
		.header img {
			height: 70px;
			width: 70px;
			vertical-align: middle;
		}
		
		.info {
			flex: 5;
			font-size: 14px;
			line-height: 24px;
		}
		
		.change-btn {
			flex: 2;
		}
		
		.change-btn button {
			vertical-align: middle;
			margin-top: 18px;
		}
		
		.goods-score {
			font-size: 13px;
		}
		/*货品*/
		
		.search-box {
			display: flex;
			padding: 10px 0;
			height: 50px;
		}
		
		.tag-box {
			flex: 4;
		}
		
		.mui-select {
			width: 80%;
			margin-left: 10%;
			border: 1px solid #C0C0C0;
			border-radius: 6px;
			line-height: 24px;
			font-size: 14px;
			color: #ACACB4;
			text-indent: 6px;
			display: inline-block;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
		
		.mui-select:before {
			top: 1px;
			right: 5px;
		}
		
		.goods-type-box {
			flex: 3;
		}
		
		.goodsname-box,.barCode-box {
			flex: 4;
			padding-left: 5%
		}
		
		.mui-input-row input {
			height: 26px;
			line-height: 24px;
			font-size: 14px;
		}
		
		.mui-input-row .mui-input-clear~.mui-icon-clear {
			top: 3px;
		}
		
		.search-btn-box {
			flex: 2;
		}
		
		.search-btn {
			border: 1px solid transparent;
			background-color: #FF9800;
			color: #fff;
			height: 28px;
			line-height: 26px;
			text-align: center;
			width: 80%;
			margin-left: 10%;
			border-radius: 2px;
			font-size: 14px;
		}
		.modify-btn {
			background-color: #FF9800;
			border-color: #FF9800;
			color: #FFFFFF;
		}
		
		.modify-btn:active {
			background-color: #ef9a60;
		}
		
		.line {
			margin: 0 5% 0px;
			height: 0;
		}
		/*滚动区*/
		
		.mui-scroll-wrapper {
			top: 130px;
			bottom: 39px;
		}
		
		ul,
		li {
			list-style: none;
			margin: 0;
			padding: 0;
		}
		/*礼品*/
		
		ul {
			padding-bottom: 10px;
		}
		
		li {
			margin-top: 15px;
		}
		
		.goods-each {
			width: 80%;
			margin-left: 10%;
			height: 16.2rem;
		}
		
		.goods-each img {
			width: 100%;
		}
		
		.goods-each div:nth-child(1) {
			position: relative;
		}
		
		.goods-each .id {
			position: absolute;
			bottom: 5px;
			width: 100%;
			background-color: rgba(52, 52, 52, .5);
			color: #FFFFFF;
			text-align: center;
			font-size: 14px;
		}
		
		.goods-name {
			font-size: 13px;
		}
		
		.goods-each div:nth-child(1) {
			position: relative;
		}
		
		.goods-id {
			font-size: 13px;
		}
		
		.mui-icon-minus:before,
		.mui-icon-plus:before {
			margin-left: calc(50% - 12px);
		}
		
		.change-num {
			height: 24px;
			text-align: center;
			font-size: 13px;
			line-height: 24px;
			color: #251414;
		}
		/*底部*/
		
		.flex {
			display: flex;
		}
		
		.flex-item {
			flex: 1;
		}
		
		footer {
			height: 41px;
			line-height: 41px;
			background-color: #fff;
			position: absolute;
			bottom: 0;
			width: 100%;
			text-align: center;
			font-size: 15px
		}
		
		footer:before {
			content: '';
			height: 1px;
			position: absolute;
			right: 0;
			bottom: 41px;
			width: 100%;
			transform: scaleY(.5);
			background-color: #acacb4;
		}
		
		.exchange-next-btn {
			background-color: #FF9800;
			height: 36px;
			line-height: 36px;
			color: #fff;
			width: 98%;
			margin: 0 auto;
			margin-top: 2px;
		}
		/*加载*/
		
		.mui-pull-bottom-pocket {
			visibility: visible;
		}
		
		.mui-pull-bottom-pocket .mui-pull-loading {
			visibility: visible;
		}
		/**/
		
		.no {
			text-align: center;
			font-size: 14px;
			line-height: 30px;
		}
	</style>

	<body>
		<div class="mui-content">
			<div class="user-info flex vux-1px-b">
				<div class="header">
					<img src="" alt="" />
				</div>
				<div class="info">
					<div></div>
					<div>ID：</div>
					<div>当前积分：</div>
				</div>
				<div class="change-btn">
					<button type="button" class="mui-btn mui-btn-primary modify-btn mui-action-back">修改</button>
				</div>
			</div>
			<!--货品-->
			<div class="goods-list">
				<div class="search-box">
					<!--<div class="goods-type-box">
        		<div class="vux-1px">
        			全部
        		</div>
        	</div>-->
					<div class="goodsname-box">
						<div class="mui-input-row">
							<input type="text" class="mui-input-clear search-input" placeholder="请输入名称">
						</div>
					</div>
          <div class="barCode-box">
            <div class="mui-input-row">
              <input type="text" class="mui-input-clear search-input" placeholder="请输入货号">
            </div>
          </div>
					<div class="search-btn-box">
						<div class="search-btn">
							查找
						</div>
					</div>
				</div>
				<div class="line vux-1px-b"></div>
				<!--礼品-->
				<div id="refreshContainer" class="mui-scroll-wrapper">
					<div class="mui-scroll">
						<ul class="goodsList mui-row">

						</ul>
						<script id="goods-List" type="text/html">
							<%if(list.length>0){%>
							<% for(var i=0; i<list.length; i++) {%>
							<li class="mui-col-sm-6 mui-col-xs-6">
								<div class="goods-each">
									<div>
										<img src="<%= imgPath+list[i].wareGoods.cutImg%>" alt="" />
										<div class="id">ID:
											<%=  list[i].wareGoods.wareGoodsId%>
										</div>
									</div>
									<div class="goods-name">

										<%=list[i].wareGoods.name%>
									</div>
									<div class="goods-id">库存：
										<%=list[i].shopGoodsAmount.amount%>
									</div>
									<div class="goods-score">门店礼品积分：
										<%=  list[i].actScore?list[i].actScore.score : list[i].shopGoodsAmount.score ? list[i].shopGoodsAmount.score : list[i].wareGoods.exchangeScore   %>
									</div>
									<div class="add-reduce mui-row">
										<span data-index='<%=i%>' class="reduce-icon mui-icon mui-icon-minus mui-col-sm-4 mui-col-xs-4"></span>
										<div class="change-num mui-col-sm-4 mui-col-xs-4 vux-1px">0</div>
										<span data-index='<%=i%>' class="add-icon mui-icon mui-icon-plus mui-col-sm-4 mui-col-xs-4"></span>
									</div>
								</div>
							</li>
							<%}%>
							<%} else{%>
							<p class="no">暂无数据</p>
							<%}%>
						</script>
						<!--加载中-->
						<div class="mui-pull-bottom-pocket">
							<div class="mui-pull">
							</div>
						</div>
						<!--加载中-->
					</div>
				</div>
				<!---->
				<!--底部-->
				<footer class="withdraw-btn-box">
					<div class="exchange-next-btn">
						下一步
					</div>
				</footer>
				<!---->
			</div>
		</div>
		<script src="../config.js"></script>
		<script src="../js/mui.min.js"></script>
		<script src="../js/template-native.js"></script>
		<script type="text/javascript">
			mui.init()
			var currentShopObj = {},
				userInfo = {},
				params = {
					tagIds: config.exceptTag,
					goodsName: '',
          barCode: '',
					pageNo: 1,
					pageCount: 10,
					shopId: '',
					upperStyle:5
				},
				type= '',
				qrData= '',
				pageTatol = 1,
				isLoading = false,
				goodsList = [],
				returnInfo = {
					merchantId:'',
					storeId: '',
					storeName: '',
					header: '',
					userId: '',
					openId: '',
					userNick: '',
					userScore: '',
					goods: []
				}
			mui.plusReady(function() {
				scroll()
				//      getTag()
				receiveParams()
				setUser()
				getGoods()
				bindEvent()
				//滚动监听
				document.querySelector('.mui-scroll-wrapper').addEventListener('scrollend', function(e) {
					if(e.detail.y <= e.detail.maxScrollY) {
						if(isLoading === false) {
							if(++params.pageNo <= pageTatol) {
								getGoods()
							} else {
								setLoading(2)
							}
						}
					}
				});
			})

			function receiveParams() {
				var self = plus.webview.currentWebview()
				currentShopObj = self.currentShopObj
				if(self.type) {
					type = self.type
					userInfo = self.res
					qrData = self.data
				} else {
					userInfo = self.userInfo
					returnInfo.storeId = params.shopId = self.currentShopObj.storeId
					returnInfo.storeName = self.currentShopObj.storeName
					returnInfo.userId = userInfo.userId
					returnInfo.openId = userInfo.openId
					returnInfo.header = userInfo.header
					returnInfo.userNick = userInfo.userNick
					returnInfo.merchantId = self.currentShopObj.merchantId
				}

			}
			//监听
			window.addEventListener('changeNum', function(e) {
				returnInfo.goods = e.detail.goods
				for(var p = 0; p < returnInfo.goods.length; p++) {
					for(var j = 0; j < goodsList.length; j++) {
						if(returnInfo.goods[p].goodsId == goodsList[j].wareGoods.wareGoodsId) {
							document.querySelectorAll(".change-num")[j].innerText = returnInfo.goods[p].amount
						}
					}
				}
			})

			//头像
			function setUser() {
				var userI = document.querySelectorAll(".info>div")
				if(type === 4) { //手机游戏
					var nowName = userInfo.userNick
					if(userInfo.userNick) {
						userI[0].innerText = userInfo.userNick
					} else {
						userI[0].innerText = '--'
					}
					userI[1].innerText = 'ID：' + userInfo.userId
					userI[2].innerText = '当前彩票：' + userInfo.userScore
					var headImg
					if(userInfo.userHead.indexOf('http')===-1){
						headImg = config.imgPath + userInfo.userHead
					} else {
						headImg = userInfo.userHead
					}
					document.querySelector(".header img").setAttribute('src', headImg)
				} else { //普通会员中心
					if(userInfo.userName) {
						userI[0].innerText = userInfo.userName
					} else {
						userI[0].innerText = '--'
					}
					userI[1].innerText = 'ID：' + userInfo.userId
					userI[2].innerText = '当前积分：' + userInfo.point
					var headImg
					if(userInfo.header.indexOf('http')===-1){
						headImg = config.imgPath + userInfo.header
					} else {
						headImg = userInfo.header
					}
					document.querySelector(".header img").setAttribute('src',headImg)
				}
			}

			function scroll() {
				//滚动
				mui('.mui-scroll-wrapper').scroll({
					scrollY: true,
					bounce: true,
					deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006，
				});
			}
			//获取商品信息
			function getGoods() {
				this.isLodaing = true
				console.log('/shopGoods/checkLike')
				setLoading(1)
				config.ajax({
					url: '/shopGoods/checkLike',
					data: params,
					success: function(res) {
						if(res.result === 1) {
							pageTatol = res.pageList.pageTatol
							if(params.pageNo === 1) {
								goodsList = res.pageList.data
								setPage()
							} else {
								res.pageList.data.forEach(function(item) {
									goodsList.push(item)
								})
								setPage()
							}
							console.log(JSON.stringify(goodsList))
							setLoading(0)
							setTimeout(function() {
								isLoading = false
							}, 1500)
						} else {
							setLoading(0)
							setPage([])
							mui.toast(res.errormsg)
							setTimeout(function() {
								isLoading = false
							}, 1500)
						}
					}
				})
			}
			//设置加载状态
			function setLoading(type) {
				switch(type) {
					case 1:
						document.querySelector(".mui-pull").innerHTML = '<div class="mui-pull-loading mui-icon mui-spinner"></div>\
						<div class="mui-pull-caption">正在加载</div>'
						break
					case 2:
						document.querySelector(".mui-pull").innerHTML = '<div class="mui-pull-caption">没有更多</div>'
						break
					case 0:
						document.querySelector(".mui-pull").innerHTML = ''
						break
				}
			}
			//获取用途
			//    function getTag() {
			//      var _this = this
			//      config.ajax({
			//        type: 'post',
			//        url: config.basePath + '/tag/get.do',
			//        data: {
			//          tagDescribe: ''
			//        },
			//        headers: {
			//          'Content-Type': 'application/json'
			//        },
			//        success: function(res) {
			//          if(res.result === 1) {
			//            res.tags.forEach(function(item) {
			//              if(item.tagDescribe.indexOf('兑换') !== -1) {
			//                params.tagIds.push(item.tagId)
			//              }
			//            })
			//            getGoods()
			//          }
			//        }
			//      })
			//    }

			function setPage() {
				var html = template('goods-List', {
					list: goodsList,
					imgPath: config.imgPath
				})
				mui('.goodsList')[0].innerHTML = html
			}

			function bindEvent() {
				document.querySelector(".search-btn").addEventListener('tap', function() {
					params.goodsName = document.querySelector(".goodsname-box input").value
					params.barCode = document.querySelector(".barCode-box input").value
					params.pageNo = 1
					mui('.mui-scroll-wrapper').scroll().scrollTo(0, 0, 100)
					getGoods()
				})
				//    	减少
				mui(".goodsList").on('tap', '.reduce-icon', function() {
					var index = this.getAttribute('data-index')
					var addnum = document.querySelectorAll(".change-num")[index].innerText * 1
					var btnArray = ['取消', '确定'];
					mui.prompt('请输入减少数量', 0, '减少', btnArray, function(e) {
						if(e.index == 1) {
							if(e.value) {
								if(addnum - e.value >= 0) {
									document.querySelectorAll(".change-num")[index].innerText = addnum - e.value * 1
									for(var i = 0; i < returnInfo.goods.length; i++) {
										if(returnInfo.goods[i].goodsId == goodsList[index].wareGoods.wareGoodsId) {
											if(addnum - e.value * 1 > 0) {
												returnInfo.goods[i].amount = addnum - e.value * 1
											} else {
												returnInfo.goods.splice(index, 1)
											}
										}
									}
								} else {
									mui.toast('数量错误!')
								}
							}
						}
					}, 'div')
					document.querySelector('.mui-popup-input input').type = 'number'
				})
				//增加
				mui(".goodsList").on('tap', '.add-icon', function(e) {
					var index = this.getAttribute('data-index')
					var addnum = document.querySelectorAll(".change-num")[index].innerText * 1
					var btnArray = ['取消', '确定'];
					var ifAdd = true
					mui.prompt('请输入新增数量', 0, '增加', btnArray, function(e) {
						if(e.index == 1) {
							if(e.value) {
								document.querySelectorAll(".change-num")[index].innerText = addnum + e.value * 1
								for(var i = 0; i < returnInfo.goods.length; i++) {
									if(returnInfo.goods[i].goodsId == goodsList[index].wareGoods.wareGoodsId) {
										returnInfo.goods[i].amount = addnum + e.value * 1
										ifAdd = false
									}
								}
								if(ifAdd) {
									var arr = {}
									arr.cutImg = goodsList[index].wareGoods.cutImg
									arr.goodsName = goodsList[index].wareGoods.name
									arr.goodsId = goodsList[index].wareGoods.wareGoodsId
									arr.score = goodsList[index].actScore ? goodsList[index].actScore.score : goodsList[index].shopGoodsAmount.score ? goodsList[index].shopGoodsAmount.score : goodsList[index].wareGoods.exchangeScore
                  arr.amount = addnum + e.value * 1
									arr.totalNum = goodsList[index].shopGoodsAmount.amount
									arr.goodsPrice = goodsList[index].wareGoods.storagePrizeAvg
									if(goodsList[index].actScore){
										arr.actId=goodsList[index].actScore.actId
									}
									returnInfo.goods.push(arr)
								}
							}
						}
					}, 'div')
					document.querySelector('.mui-popup-input input').type = 'number'
				})
				//
				document.querySelector(".exchange-next-btn").addEventListener('tap', function() {
					nextStep()
				})
			}
			//		下一步
			function nextStep() {
				var title = '兑换'
				console.log(JSON.stringify(currentShopObj))
				console.log('returnInfo',JSON.stringify(returnInfo))
//				console.log(JSON.stringify(currentShopObj))
				mui.openWindow({
					url: './exchange-all.html',
					id: 'exchange-all',
					styles: {
						top: 0, //新页面顶部位置
						bottom: 0, //新页面底部位置         
						titleNView: {
							titleText: title,
							titleColor: "#FFFFFF",
							titleSize: "17px",
							backgroundColor: "#FF6800",
							autoBackButton: true,
							//                homeButton: true,
							buttons: [{
								float: "right",
								fontSize: "18px",
								fontSrc: "_www/fonts/iconfont.ttf", //wap2app内置字体文件
								text: "\ue602",
								onclick: function() {
									var allPage = plus.webview.all()
									var nowPage = plus.webview.getWebviewById('index')
									for(var i = 0; i < allPage.length; i++) {
										if(allPage[i].getURL() !== nowPage.getURL()) {
											plus.webview.close(allPage[i]);
										}
									}
								}
							}],
							splitLine: {
								color: "#CCCCCC",
								height: "1px"
							}
						}
					},
			
					extras: {
						currentShopObj: currentShopObj,
						returnInfo: returnInfo,
						userInfo: userInfo,
						type: type,
						qrData: qrData
					}
				})
			}
		</script>
	</body>

</html>